<?php

namespace app\admin\controller;

use think\admin\Controller;
use think\facade\Request;

/**
 * 敏感词库
 * Class Sensitive
 * @package app\admin\controller
 */
class Sensitive extends Controller
{

    protected $table = 'Other';//测试表，使 _page() 等方法可以调用 无意义。随便创建一个字段 或者 指定其它表也可以


    /**
     * 敏感词列表
     * @auth true
     * @menu true
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     *
     * 词库整合自github https://github.com/jkiss/sensitive-words
     */
    public function index()
    {
        $this->title = '敏感词汇';
        $data['info'] = $this->getSensitiveArray();
        $keywords = input('keywords');//搜索关键词
        $sort = input('sort');//排序
        $limit = empty(input('limit')) ? 20 : input('limit');//显示数量
        $page = empty(input('page')) ? 1 : input('page');//页码
        $start = ($page - 1) * $limit;//偏移量，当前页-1乘以每页显示条数

        if (!empty($keywords)) $data['info'] = searchArray($data['info'], $keywords);//匹配搜索数据

        if ($sort == 'desc') krsort($data['info']);//倒叙
        $list = array_slice($data['info'], $start, $limit);//分页显示
        $this->list = $list;
        $this->mySort = $sort;
        $this->_page($this->table, $page, true, count($data['info']), $limit, 'index');
    }


    /**
     * 敏感字符串测试
     * @auth true
     * @menu true
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function checkString()
    {
        if (Request::isPost()) {
            $data = $this->_vali([
                'check_string.require' => '请输入待检测字符串！',
            ]);

            $arr = $this->actionCheckStr($data['check_string']);
            $this->success($arr['info'], '', $arr['code']);
        }
        $this->_form($this->table, 'check_string');
    }

    /**
     * 检测敏感字符串，并返回敏感词
     * @param $content
     * @return array
     */
    protected function actionCheckStr($content)
    {
        error_reporting(0);
        foreach ($this->getSensitiveArray() as $val) {
            if (strstr($content, $val['val']) !== false) {
                return [
                    'code' => 5,
                    'info' => '包含敏感词：' . $val['val']
                ];
            }
        }
        return [
            'code' => 6,
            'info' => '未检查到敏感词汇'
        ];
    }


    /**
     * 添加词汇
     * @auth true
     * @menu true
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function addWord()
    {
        if (Request::isPost()) {
            $this->_vali([
                'new_word.require' => '词汇不能为空！',
            ]);
            $file = fopen(getSensitiveFile(), "a");//a 文件追加
            $str = "\n" . input('new_word');
            fwrite($file, $str);
            fclose($file);
            sysoplog('添加词汇');
            $this->success();
        }
        $this->_form($this->table, 'form');
    }

    /**
     * 删除指定词汇
     * @auth true
     * @menu true
     *
     */
    public function delWord()
    {

        $this->_vali([
            'word.require' => '缺少删除词汇',
        ]);

        $oldWord = $this->getSensitiveArray();

        foreach ($oldWord as $key => $val) {
            if ($val['val'] == input('word')) {
                unset($oldWord[$key]);
            }
        }

        $str = '';
        foreach ($oldWord as $res) {
            $str .= $res['val'] . "\n";
        }

        $file = fopen(getSensitiveFile(), "w");//文件写入
        fwrite($file, $str);
        fclose($file);
        sysoplog('删除词汇');
        $this->success();
    }

    /**
     * 敏感词库文本获取
     * @return array|mixed
     */
    protected function getSensitiveArray()
    {

        $lines = file(getSensitiveFile());
        $newsLines = [];
        $mark = [" ", "　", "\t", "\n", "\r"];
        foreach ($lines as $word) {
            $newsLines[] = str_replace($mark, '', $word);//此操作去掉换行、空格等
        }
        $newsLines = array_values(array_unique($newsLines));//去重一下并且初始化下标

        //重新给数组键名
        $data['info'] = [];
        foreach ($newsLines as $k => $v) {
            $data['info'][] = [
                'no' => $k + 1,
                'val' => $v
            ];
        }
        return $data['info'];
    }


}